package com.asuka.controller.user;

import com.asuka.context.BaseContext;
import com.asuka.entity.AddressBook;
import com.asuka.result.Result;
import com.asuka.service.AddressBookService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/user/addressBook")
@RestController
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;


    @GetMapping("/list")
    public Result<List<AddressBook>> list(){
        List<AddressBook> list = addressBookService.selectListByUserId();
        return Result.success(list);
    }


    @GetMapping("/default")
    public Result<AddressBook> selectDefaultAdress(){
        AddressBook adress = addressBookService.selectDefaultAdress();

        return adress == null ? Result.success(adress) : Result.error("没有查到默认地址!!!");
    }

    @GetMapping("/{id}")
    public Result<AddressBook> selectById(@PathVariable Long id){
        AddressBook address = addressBookService.selectById(id);

        return Result.success(address);
    }




    @PostMapping
    public Result insert(@RequestBody AddressBook addressBook){
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());

        addressBookService.insert(addressBook);

        return Result.success();
    }


    @PutMapping("/default")
    public Result updateDefaultAdress(@RequestBody AddressBook addressBook){
        addressBookService.updateDefaultAdress(addressBook.getId());
        return Result.success();
    }


    @PutMapping
    public Result updateById(@RequestBody AddressBook address){

        addressBookService.updateById(address);
        return Result.success();
    }


    @DeleteMapping
    public Result deleteById(Long id){
        addressBookService.deleteById(id);
        return Result.success();
    }

}
